import json
import time

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from geetest.geetest_v3 import GeeTest3
from main_v2 import scroll_down

# Chrome浏览器
driver = webdriver.Chrome()


def print_hi(name):
  # Use a breakpoint in the code line below to debug your script.
  print(f'Hi, {name}')  #
  # 最大化
  driver.maximize_window()

  # driver.get(
  #     "https://www.shein.com.mx/1pc-Rhinestone-Butterfly-Tassel-Hair-Hoop-p-20093905.html?src_identifier=st%3D3%60sc%3DVinchas%60sr%3D0%60ps%3D6&src_module=search&src_tab_page_id=page_store1710428377649&mallCode=1&pageListType=4")
  data = requests.get('http://localhost:6253/getRandSyncDetail')
  first = True
  while data.text != None:
    # 页面缩小
    zoom_out = "document.body.style.zoom='0.1'"
    driver.execute_script(zoom_out)
    try:
      updateData(data.text,first)
    except:
      pass
    first = False
    data = requests.get('http://localhost:6253/getRandSyncDetail')

def updateData(data,first):
  print('当前正在爬：' + data)
  # 产品
  product = dict()

  driver.get(data)
  if first == True:
    time.sleep(30)
  else:
    time.sleep(3)

  # 滑动到页面的特定位置，例如滑动到页面的底部
  driver.execute_script(
      'document.querySelectorAll(\'.she-close\')[0]?.click()')
  driver.execute_script(
      'document.querySelectorAll(\'.dialog-top__close-btn\')[0]?.click()')
  # 五级分类+
  typeList = driver.find_elements(By.CSS_SELECTOR, '.bread-crumb__item-link')
  # 下滑
  scroll_down(driver)
  product['type_1'] = typeList[0].text
  product['type_2'] = typeList[1].text
  product['type_3'] = typeList[2].text
  product['type_4'] = typeList[3].text
  product['type_5'] = typeList[4].text
  product['sku'] = driver.find_element(By.CSS_SELECTOR,
                                       '.product-intro__head-sku').text.removeprefix(
      'SKU: ')
  # 总评论数
  allCommentCountElements = driver.find_elements(By.CSS_SELECTOR,
                                                 '.product-intro__head-reviews-text')
  allCommentCount = 0
  if len(allCommentCountElements) > 0:
    allCommentCount = allCommentCountElements[0].text
  product['allCommentCount'] = allCommentCount




  product['productPrice'] = driver.find_element(By.CSS_SELECTOR,
                                                '.from  span').text
  # 库存数量
  stockCount = None
  stockCountElements = driver.find_elements(By.CSS_SELECTOR,
                                            '.product-intro__qty-orange')
  # 是否参与闪购
  flashElements = driver.find_elements(
      By.CSS_SELECTOR,'.product-intro__PriceBannerType-headLeft'
  )
  if len(flashElements) > 0:
    product['joinQuick'] =flashElements[0].text
  if len(stockCountElements) > 0:
    stockCount = stockCountElements[0].text
  product['stockCount'] = stockCount
  sWitch = driver.find_elements(By.CSS_SELECTOR, '.c-switch')
  # 库存（缺货）情况
  product['lessFlag'] = driver.find_element(By.CSS_SELECTOR,
                                            '.product-intro__add-btn').text

  if len(sWitch) > 0:

    # 总评论数量
    product['allCommentCount'] = driver.find_element(By.CSS_SELECTOR,
                                                     'h2.j-expose__common-review-container').get_attribute('aria-label')
    # 总评论分数
    product['allCommentScore'] = driver.find_element(By.CSS_SELECTOR,
                                                     '.rate-num').text
    # 切换成本土
    driver.execute_script("document.querySelectorAll('.c-switch')[0].click()")
    time.sleep(5)
    # 本土评论数量
    product['locationCommentCount'] = driver.find_element(By.CSS_SELECTOR,
                                                          'h2.j-expose__common-review-container').get_attribute('aria-label')
    # 本土评论分数
    product['locationCommentScore'] = driver.find_element(By.CSS_SELECTOR,
                                                          '.rate-num').text
    # 切换最新评论
    driver.execute_script(
          "document.querySelectorAll('.common-reviews__select-box-list > li[data-sort-type]')[0].click()");
    # 等待5秒
    time.sleep(5)
    # 抓取第一个
    product['locationCommentLastTimeStr'] = driver.find_element(By.CSS_SELECTOR,
                                                                '.common-reviews-new__top-baseinfo .date').text
  # 展开店铺信息
  driver.execute_script(
      "document.querySelectorAll('.product-intro__brand-head')[0]?.click()");
  try:
    WebDriverWait(driver, 3).until(
        EC.presence_of_element_located(
            (By.CSS_SELECTOR, '.shop-entry__storeEntry .title'))
    )
  except:
    print('[error]:获取不到店铺名称'+data)
    return
  # 抓取店铺名称
  product['shopName'] = driver.find_element(By.CSS_SELECTOR,
                                            '.shop-entry__storeEntry .title').text
  if product['shopName']  == '':
    pass
  infoElement = driver.find_elements(By.CSS_SELECTOR, '.follow-info-line em')
  if len(infoElement) > 2:
    # 店铺分数
    product['shopScore'] = infoElement[0].text
    # 店铺的产品数量
    product['shopProductCount'] = infoElement[1].text
  else:
    # 店铺的产品数量
    product['shopProductCount'] = infoElement[0].text

  # 店铺id获取
  dataId = driver.find_element(By.CSS_SELECTOR,
                               '.shop-entry_JumpToStoreBtn').get_attribute(
      'data-id')
  product[
    'shopUrl'] = "https://www.shein.com.mx/store/home?store_code=" + dataId + "&type=selection&tab=items"
  driver.execute_script(
      'document.querySelectorAll(".product-intro__description-head")[0].click()')
  # 取出文字
  time.sleep(3)
  product['describe'] = driver.find_element(By.CSS_SELECTOR,
                                            '.product-intro__description-table').text
  print(product)
  productList = [product]
  # 发送请求
  url = 'http://localhost:6253/batchSaveOrUpdate'
  headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
  }
  print(productList)
  jsonStr = json.dumps(productList)
  print(jsonStr)
  # 直接给post方法中的json参数赋值，赋json类型的数据
  response = requests.post(url=url, headers=headers, json=productList)
  page_text = response.text
  print(page_text)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
   print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
